//package com.qy.changemachine.api;
//
//import android.os.Handler;
//import android.os.Message;
//import android.util.Log;
//
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//
//import okhttp3.Call;
//import okhttp3.Callback;
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.Response;
//
//public class DownloadUtil {
//    public static final int DOWNLOAD_FAIL=0;
//    public static final int DOWNLOAD_PROGRESS=1;
//    public static final int DOWNLOAD_SUCCESS=2;
//    private static DownloadUtil downloadUtil;
//    private final OkHttpClient okHttpClient;
//    public static DownloadUtil getInstance() {
//        if (downloadUtil == null) {
//            downloadUtil = new DownloadUtil();
//        }
//        return downloadUtil;
//    }
//
//    private DownloadUtil() {
//        okHttpClient = new OkHttpClient();
//    }
//
//    /**
//     *
//     */
//    public void download(final String url,final String pathname,final OnDownloadListener listener){
//        this.listener=listener;
//        Request request=new Request.Builder().url(url).build();
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Message message=Message.obtain();
//                message.what=DOWNLOAD_FAIL;
//                mHandler.sendMessage(message);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                InputStream is=null;
//                byte[] buf=new byte[2048];
//                int len=0;
//                FileOutputStream fos=null;
//                //储存下载文件的目录
//                try{
//                    is=response.body().byteStream();
//                    long total=response.body().contentLength();
//                    File file=new File(pathname);
//                    //url为文件名，.mp4为文件类型，需要什么文件名和文件类型可直接改变。
//                    fos=new FileOutputStream(file);
//                    long sum=0;
//                    while((len = is.read(buf))!=-1){
//                        fos.write(buf,0,len);
//                        sum+=len;
//                        int progress=(int)(sum*1.0f/total*100);
//                        //下载中
//                        Message message=Message.obtain();
//                        message.what=DOWNLOAD_PROGRESS;
//                        message.obj=progress;
//                        mHandler.sendMessage(message);
//                    }
//                    fos.flush();
//                    //下载完成
//                    Message message=Message.obtain();
//                    message.what=DOWNLOAD_SUCCESS;
//                    message.obj=file.getAbsolutePath();
//                    mHandler.sendMessage(message);
//
//                }catch (Exception e){
//                   Log.e("下载异常",e.getMessage());
//                }finally{
//                    try{
//                        if(is!=null)
//                            is.close();
//                    }catch (IOException e){
//
//                    }
//                    try {
//                        if(fos!=null){
//                            fos.close();
//                        }
//                    }catch (IOException e){
//
//                    }
//                }
//            }
//        });
//    }
//
//    private String getNameFromUrl(String url) {
//        return url.substring(url.lastIndexOf("/")+1);
//    }
//
//
//    private String isExistDir(String saveDir) throws IOException {
//        File downloadFile=new File(saveDir);
//        if(!downloadFile.mkdirs()){
//            downloadFile.createNewFile();
//        }
//        String savePath=downloadFile.getAbsolutePath();
//        return savePath;
//    }
//
//
//
//
//    private Handler mHandler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what){
//                case DOWNLOAD_PROGRESS:
//                    listener.onDownloading((Integer) msg.obj);
//                    break;
//                case DOWNLOAD_FAIL:
//                    listener.onDownloadFailed();
//                    break;
//                case DOWNLOAD_SUCCESS:
//                    listener.onDownloadSuccess((String) msg.obj);
//                    break;
//            }
//        }
//    };
//
//
//    OnDownloadListener listener;
//    public interface OnDownloadListener{
//        /**
//         * 下载成功
//         */
//        void onDownloadSuccess(String path);
//        /**
//         * 下载进度
//         * @param progress
//         */
//        void onDownloading(int progress);
//        /**
//         * 下载失败
//         */
//        void onDownloadFailed();
//    }
//}

package com.qy.changemachine.api;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.qy.changemachine.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {

    public static final int DOWNLOAD_FAIL = 0;
    public static final int DOWNLOAD_PROGRESS = 1;
    public static final int DOWNLOAD_SUCCESS = 2;

    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;
    private WeakReference<OnDownloadListener> listenerRef; // 使用弱引用避免内存泄漏
    private final Handler mHandler; // 绑定到主线程的 Handler

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
        mHandler = new Handler(Looper.getMainLooper()) { // 确保 Handler 在主线程中运行
            @Override
            public void handleMessage(Message msg) {
                OnDownloadListener listener = listenerRef.get();
                if (listener != null) {
                    switch (msg.what) {
                        case DOWNLOAD_PROGRESS:
                            listener.onDownloading((Integer) msg.obj);
                            break;
                        case DOWNLOAD_FAIL:
                            listener.onDownloadFailed((String) msg.obj);
                            break;
                        case DOWNLOAD_SUCCESS:
                            listener.onDownloadSuccess((String) msg.obj);
                            break;
                    }
                }
            }
        };
    }

    public static DownloadUtil getInstance() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    /**
     * 下载文件
     *
     * @param url      文件下载地址
     * @param pathname 文件保存路径
     * @param listener 下载监听器
     */
    public void download(final String url, final String pathname, final OnDownloadListener listener) {
        this.listenerRef = new WeakReference<>(listener); // 使用弱引用持有监听器

        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.INSTANCE.d("DownloadUtil", "下载失败: " + e.getMessage());
                Message message = Message.obtain();
                message.what = DOWNLOAD_FAIL;
                message.obj =  e.getMessage();
                mHandler.sendMessage(message); // 发送失败消息
            }

            @Override
            public void onResponse(Call call, Response response){
                InputStream is = null;
                FileOutputStream fos = null;
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(pathname);

                    // 确保父目录存在
                    File parentDir = file.getParentFile();
                    if (parentDir != null && !parentDir.exists()) {
                        parentDir.mkdirs();
                    }

                    fos = new FileOutputStream(file);
                    byte[] buf = new byte[2048];
                    int len;
                    long sum = 0;

                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);

                        // 发送进度消息
                        Message message = Message.obtain();
                        message.what = DOWNLOAD_PROGRESS;
                        message.obj = progress;
                        mHandler.sendMessage(message);
                    }

                    fos.flush();

                    // 发送成功消息
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_SUCCESS;
                    message.obj = file.getAbsolutePath();
                    mHandler.sendMessage(message);

                } catch (Exception e) {
                    LogUtil.INSTANCE.d("DownloadUtil", "下载异常: " + e.getMessage());
                    // 发送失败消息
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_FAIL;
                    mHandler.sendMessage(message);
                } finally {
                    try {
                        if (is != null) is.close();
                        if (fos != null) fos.close();
                    } catch (IOException e) {
                        LogUtil.INSTANCE.d("DownloadUtil", "关闭流异常: " + e.getMessage());
                    }
                }
            }
        });
    }

    /**
     * 下载监听器接口
     */
    public interface OnDownloadListener {
        /**
         * 下载成功
         *
         * @param path 文件保存路径
         */
        void onDownloadSuccess(String path);

        /**
         * 下载进度
         *
         * @param progress 当前进度（0-100）
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed(String msg);
    }
}